//
//  ShoppingViewController.m
//  UGoods
//
//  Created by 宝银 on 16/1/15.
//  Copyright © 2016年 蓝鸥科技.李贺. All rights reserved.
//

#import "ShoppingViewController.h"
#import "LHAFNetworkTool.h"
#import "FindModel.h"
#import "BaseCollectionView.h"
#import "BaseTableView.h"
#import "BaseView.h"
#import "BaseLabel.h"
#import "GoodsCollectionViewCell2.h"
#import "BuyDetailViewController.h"
#import "DataBaseManager.h"
#import "ShoppingTableViewCell.h"
#import <MJRefresh.h>
#import "ConstantsDefine.h"
@interface ShoppingViewController ()<UITableViewDataSource, UITableViewDelegate, UICollectionViewDelegate, UICollectionViewDataSource>

@property (nonatomic, retain) BaseTableView *tableView;
@property (nonatomic, retain) BaseCollectionView *collectionView;
@property (nonatomic, retain) NSMutableArray *dataArray;
@property (nonatomic, retain) NSMutableArray *listArray;

@end

@implementation ShoppingViewController

- (void)dealloc
{
    [_tableView release];
    [_collectionView release];
    [_dataArray release];
    [_listArray release];
    [super dealloc];
}

- (void)handleData {

    self.dataArray = [[DataBaseManager shareInstance] select];
    [self.tableView.mj_header endRefreshing];
    if (self.dataArray.count == 0) {
        BaseView *backView = [[BaseView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height - 350 * HEIGHT)];
        //    backView.backgroundColor = [UIColor redColor];
        self.tableView.tableHeaderView = backView;
        [backView release];
        
        UIImageView *aimageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 100 * WIDTH, 100 * HEIGHT)];
        aimageView.center = backView.center;
        aimageView.image = [UIImage imageNamed:@"iconfont-gouwu-5"];
        [backView addSubview:aimageView];
        [aimageView release];
        
        BaseLabel *alabel = [[BaseLabel alloc] initWithFrame:CGRectMake(0, 0, 300 * WIDTH, 20 * HEIGHT)];
        alabel.center = CGPointMake(backView.center.x, backView.frame.size.height - 80 * HEIGHT);
        alabel.text = @"唉呀妈呀，你的购物袋空空如也 ! !";
        alabel.font = [UIFont fontWithName:@"Zapfino" size:15];
        alabel.textAlignment = NSTextAlignmentCenter;
        [backView addSubview:alabel];
        [alabel release];
        
    }
}

// 下拉刷新
- (void)addHeaderRefresh {
    MJRefreshGifHeader *header = [MJRefreshGifHeader headerWithRefreshingBlock:^{
        [self.dataArray removeAllObjects];
        [self handleData];
    }];
    // 设置普通状态的动画图片
    NSArray *idleImages = @[[UIImage imageNamed:@"loading_0"]];
    [header setImages:idleImages forState:MJRefreshStateIdle];
    // 设置即将刷新状态的动画图片（一松开就会刷新的状态
    NSArray *pullingImages = @[[UIImage imageNamed:@"loading_0"]];
    [header setImages:pullingImages forState:MJRefreshStatePulling];
    // 设置正在刷新状态的动画图片
    NSMutableArray *refreshingImages = [NSMutableArray array];
    for (NSInteger i = 0; i < 24; i++) {
        [refreshingImages addObject:[UIImage imageNamed:[NSString stringWithFormat:@"loading_%ld", i]]];
    }
    [header setImages:refreshingImages forState:MJRefreshStateRefreshing];
    // 设置所有数据加载完毕的动画图片
    NSArray *NoMoreDataImages = @[[UIImage imageNamed:@"loading_0"]];
    [header setImages:NoMoreDataImages forState:MJRefreshStateNoMoreData];
    
    self.tableView.mj_header = header;
    
    // 隐藏时间-
    header.lastUpdatedTimeLabel.hidden = YES;
    
    // 隐藏状态
    header.stateLabel.hidden = YES;
    
    [self.tableView.mj_header beginRefreshing];
}


- (void)createTableView {
    self.tableView = [[BaseTableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    [self.view addSubview:_tableView];
    [_tableView release];
    [_tableView registerClass:[ShoppingTableViewCell class] forCellReuseIdentifier:@"cell"];
    
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    FindModel *model = self.dataArray[indexPath.row];
    ShoppingTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    cell.model = model;
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 100;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    BuyDetailViewController *buy = [[BuyDetailViewController alloc] init];
    FindModel *model = self.dataArray[indexPath.row];
    buy.model = model;
    [self.navigationController pushViewController:buy animated:YES];
}


- (void)handleHeaderData {
    NSString *str = @"http://api.ujipin.com/v2/app/ios/phone/v3/index/getFlashSaleList?channel=appstore&idfa=1EF25F55-6367-4567-B0D5-82DF4F1557CD&user_id=470825&plantform=iphone&version=314";
    [LHAFNetworkTool getUrl:str body:nil response:LHJSON requestHeadFile:nil success:^(NSURLSessionDataTask *task, id resposeObject) {
        NSArray *array = resposeObject[@"data"][@"list"];
        
        self.listArray = [FindModel modelHandleWithArray:array];
        
        [self.collectionView reloadData];
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        NSLog(@"请求失败：%@", error);
    }];
}


- (void)createTableViewFooter {
    BaseView *backView = [[BaseView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 210 * HEIGHT)];
    self.tableView.tableFooterView = backView;
    [backView release];
    
    BaseLabel *alabel = [[BaseLabel alloc] initWithFrame:CGRectMake(10 * WIDTH, 5 * HEIGHT, 200 * WIDTH, 20 * HEIGHT)];
    alabel.text = @"限时抢购, 还不快来";
    alabel.font = [UIFont systemFontOfSize:15];
    [backView addSubview:alabel];
    [alabel release];
    
    UICollectionViewFlowLayout *layout = [[[UICollectionViewFlowLayout alloc] init] autorelease];
    layout.itemSize = CGSizeMake(130 * WIDTH, 170 * HEIGHT);
    layout.minimumInteritemSpacing = 10 * WIDTH;
    layout.minimumLineSpacing = 10 * HEIGHT;
    layout.sectionInset = UIEdgeInsetsMake(0, 5 * WIDTH, 0, 5 * WIDTH);
    layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    
    self.collectionView = [[BaseCollectionView alloc] initWithFrame:CGRectMake(0, 30 * HEIGHT, self.view.frame.size.width, 170 * HEIGHT) collectionViewLayout:layout];
    _collectionView.delegate = self;
    _collectionView.dataSource = self;
    self.collectionView.showsHorizontalScrollIndicator = NO;
    [backView addSubview:_collectionView];
    [_collectionView release];
    [_collectionView registerClass:[GoodsCollectionViewCell2 class] forCellWithReuseIdentifier:@"cell"];
}

// cell 个数
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.listArray.count;
}

// cell设置
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    // section: 分区
    // item：表示cell
    
    // 获取cell
    GoodsCollectionViewCell2 *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];
    FindModel *model = _listArray[indexPath.item];
    cell.model = model;
    //    cell.backgroundColor = [UIColor redColor];
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    BuyDetailViewController *buy = [[BuyDetailViewController alloc] init];
    FindModel *model = _listArray[indexPath.item];
    buy.goods_id = [NSString stringWithFormat:@"%@", model.myID];
    [self.navigationController pushViewController:buy animated:YES];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [[DataBaseManager shareInstance] openDB];
     [self handleData];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.navigationItem.title = @"购 物 袋";
//    [self handleData];
    [self handleHeaderData];
    [self createTableView];

    [self createTableViewFooter];
    [self addHeaderRefresh];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
